package com.hzlx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzlx.bean.Inventory;
import com.hzlx.dao.InventoryDao;
import com.hzlx.dto.InventoryRequest;
import com.hzlx.dto.InventoryResponse;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class InventoryService {
    private final InventoryDao inventoryDao;

    public List<InventoryResponse> isInStock(List<String> skuCode) {
        log.info("Checking Inventory");// in ('sku1','sku2')
        QueryWrapper<Inventory> qw = Wrappers.<Inventory>query().in("sku", skuCode);
        return inventoryDao.selectList(qw)
                .stream()
                .map(inventory ->
                        InventoryResponse.builder()
                                .sku(inventory.getSku())
                                .isInStock(inventory.getQuantity() > 0 ? 1 : 0)
                                .quantity(inventory.getQuantity())
                                .build()
                ).collect(Collectors.toList());
    }

    public void create(InventoryRequest request) {
        Inventory inventory = Inventory.builder()
                .sku(request.getSku())
                .quantity(request.getQuantity())
                .isInStock(request.getQuantity() > 0 ? 1 : 0)
                .build();
        inventoryDao.insert(inventory);
        log.info("inventory inserted!");
    }

    public void update(InventoryRequest request){
        Inventory inventory = Inventory.builder()
                .sku(request.getSku())
                .quantity(request.getQuantity())
                .build();
        inventoryDao.update(inventory);
    }

}
